#include "productmodel.h"
#include "database/dbtabproduct.h"

ProductModel::ProductModel(int colCnt,const QString& showName,QObject* parent):QAbstractListModel(parent),mColumnCount(colCnt)
  ,mDataCount(0),mColumnName(showName)
{
    mQuery = new DataBaseQuery();
    mTabName = DBTabProduct::TAB_NAME;
}

ProductModel::~ProductModel()
{
    delete mQuery;
}

bool ProductModel::submit()
{
    beginResetModel();
    QStringList keyList;
    keyList<<mColumnName<<DBTabProduct::_HI<<DBTabProduct::_OK<<DBTabProduct::_LOW;
    mQuery->selectTable(mTabName,&keyList);
    endResetModel();
    mDataCount = mQuery->size();
    return true;
}

bool ProductModel::submitFilter(const QString &str)
{
    beginResetModel();
    mQuery->exec("select DISTINCT "+mColumnName + " from " + mTabName
                     + " where " + QString(DBTabProduct::_NAME) + " LIKE \""+ str +"%\"");
    endResetModel();
    mDataCount = mQuery->size();
    return true;
}

int ProductModel::rowCount(const QModelIndex &parent) const
{
    return (mDataCount+mColumnCount-1)/mColumnCount;
}

int ProductModel::columnCount(const QModelIndex &parent) const
{
    return mColumnCount;
}

QVariant ProductModel::data(const QModelIndex &index, int role) const
{
    if(!index.isValid())
    {
        return QVariant();
    }

    if(mQuery->seek(index.row()*mColumnCount+index.column()))
    {
        return mQuery->value(role-Qt::UserRole);
    }
    else
    {
        return QVariant();
    }
    return QVariant();
}

